package com.thinkcms.security.custom;

import com.thinkcms.core.utils.BaseContextKit;
import com.thinkcms.system.api.system.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/*
 * @Author LG
 * @Description   资源认证管理-用来认证资源是否允许访问动态验证
 * @Date 15:59 2019/4/30
 * @Param
 * @return
 **/
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {

	@Autowired
	MenuService menuService;

	@Override
	public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
			Set<String> authPerms= menuService.selectPermsByUid(BaseContextKit.getUserId());
			Set<String> needAuthSets = configAttributes.stream().map(auth -> auth.getAttribute()).collect(Collectors.toSet());
			boolean beMatch = authPerms.containsAll(needAuthSets);
			if (!beMatch) {
				//抛出该异常会执行自定义 CustomAccessDeniedHandler
				throw new AccessDeniedException("用户权限不足,请联系管理员");
			}
			return;
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	
}
